/*
 * Copyright (C) 2009  Sylvain Maucourt (smaucourt@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *
 */
package net.sylvek.where.server;

import com.google.appengine.repackaged.com.google.common.collect.Ordering;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import net.sylvek.where.entity.PMF;
import net.sylvek.where.entity.UserEntity;

import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class Users extends CachedServlet {

    @Override
    @SuppressWarnings("unchecked")
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        String[] uids = UidHelper.getArrayOfInternalUids(req.getParameter("uids"));

        List<JsonObject> result = new ArrayList<JsonObject>();

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            Query q = pm.newQuery(UserEntity.class);
            q.setRange(0, 500);
            q.declareParameters("java.util.Collection uids");
            q.setFilter("uids.contains(uid)");
            Collection<UserEntity> c = (Collection<UserEntity>) q.execute(Arrays.asList(uids));

            Iterator<UserEntity> i = c.iterator();
            while (i.hasNext()) {
                UserEntity u = i.next();
                JsonObject o = new JsonObject();
                o.addProperty("name", u.getName());
                o.addProperty("online", u.getOnline());
                String uid = UidHelper.getExternalUid(u.getUid());
                o.addProperty("uid", uid);
                o.addProperty("latitude", u.getLat());
                o.addProperty("longitude", u.getLon());
                o.addProperty("update", DateFormat.getInstance().format(u.getUpdate()));
                o.addProperty("sorting", u.getUpdate().getTime());
                result.add(o);
            }

            // jdo doesn't like contains + ordering (30 subqueries maxi)
            List<JsonObject> users = Ordering.from(new Comparator<JsonObject>() {

                @Override
                public int compare(JsonObject o1, JsonObject o2)
                {
                    long d1 = o1.get("sorting").getAsLong();
                    long d2 = o2.get("sorting").getAsLong();

                    return (int) (d2 - d1);
                }
            }).sortedCopy(result);

            resp.getWriter().print(convert(users).toString());
        } catch (Exception e) {
            JsonObject error = new JsonObject();
            error.addProperty("success", false);
            error.addProperty("error", e.getMessage());
            resp.getWriter().print(error.toString());
        } finally {
            pm.close();
            resp.getWriter().flush();
        }
    }

    private static JsonArray convert(List<JsonObject> jsons)
    {
        JsonArray result = new JsonArray();
        for (JsonObject json : jsons) {
            result.add(json);
        }
        return result;
    }
}
